<template>
  <div>
    <!-- 顶部面包屑导航 -->
    <breadcrumb-nav>
      <template v-slot:firstMenu>商品管理</template>
      <template v-slot:secondMenu>{{ menuTitle }}</template>
    </breadcrumb-nav>
    <!-- 卡片视图 -->

    <el-card class="box-card goods-add" shadow="never">
      <el-button type="primary" @click="submitGoods">确认提交商品</el-button>
    </el-card>
    <!-- 步骤条 -->
    <!--<el-steps :space="200" :active="activeIndex * 1" finish-status="success" align-center style="margin-top: 30px">
      <el-step title="基本信息"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="轮播图"></el-step>
      <el-step title="详情图"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>-->
    <el-card>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" size="small"
               label-position="left">
        <!-- tab栏区域 -->
        <el-tabs v-model="activeIndex" type="border-card" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <!--<goods-base-pane></goods-base-pane>-->
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="addForm.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品价格" prop="retail_price">
                  <el-input v-model="addForm.retail_price"
                            oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品分类" prop="category_id">
                  <el-select v-model="addForm.category_id" style="width:100%" clearable placeholder="请选择分类">
                    <el-option
                      v-for="item in categoryList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品类型" prop="goods_type">
                  <el-select v-model="addForm.goods_type" style="width:100%" clearable placeholder="请选择商品类型">
                    <el-option
                      v-for="item in goodsTypes"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品简介" prop="goods_brief">
                  <el-input v-model="addForm.goods_brief"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品编码" prop="goods_sn">
                  <el-input v-model="addForm.goods_sn"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="店铺" prop="shop_code">
                  <el-select v-model="addForm.shop_code" style="width:100%" clearable placeholder="请选择店铺">
                    <el-option
                      v-for="item in shopList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="排序" prop="sort_order">
                  <el-input v-model.number="addForm.sort_order" min="0"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="缩略图" prop="list_pic_url">
              <el-input v-model="addForm.list_pic_url"></el-input>
            </el-form-item>
            <el-form-item label="主图" prop="primary_pic_url">
              <el-input v-model="addForm.primary_pic_url"></el-input>
            </el-form-item>
            <el-form-item label="是否在售" prop="is_on_sale">
              <!--<el-input v-model.number="addForm.is_on_sale" min="0"></el-input>-->
              <el-switch
                v-model="addForm.is_on_sale"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </el-form-item>
            <!--<el-form-item label="排序" prop="sort_order">
              <el-input v-model.number="addForm.sort_order" min="0"></el-input>
            </el-form-item>-->
            <el-form-item label="描述信息" prop="goods_desc">
              <el-input v-model="addForm.goods_desc"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="1">
            <el-row>
              <el-col :span="6" style="margin-top: 25px;">
                <el-form-item label="属性名" prop="attr_name" label-width="70px">
                  <el-input v-model="add_attrs.name"></el-input>
                </el-form-item>
                <el-form-item label="属性值" prop="attr_value" label-width="70px" style="width: 100%">
                  <el-input v-model="add_attrs.value"></el-input>
                </el-form-item>
                <el-button type="primary" @click="addGoodsAttr">添加属性</el-button>
              </el-col>
              <el-col :span="18">
                <el-form-item prop="goods_attrs">
                  <el-table
                    :data="addForm.goods_attrs"
                  >
                    <el-table-column
                      prop="name"
                      label="属性名"
                      width="180">
                    </el-table-column>
                    <el-table-column
                      prop="value"
                      label="属性值">
                    </el-table-column>
                    <el-table-column label="操作" class="btns">
                      <template slot-scope="scope">
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                   @click="removeGoodsAttr(scope.$index)">删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="轮播图" name="2">
            <el-upload :action="uploadUrl" :headers="imgUploadHeaders" list-type="picture-card" :auto-upload="true" :on-success="handleImgUploadSuccess" :file-list="fileList">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handleImgPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleImgRemove(file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="previewDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
            <el-row>
              <el-col :span="6" style="margin-top: 25px;">
                <el-form-item label="地址" prop="gallery_url" label-width="70px" label-position="top">
                  <el-input v-model="add_gallery.addr"></el-input>
                </el-form-item>
                <el-button type="primary" @click="addGoodsGallery">添加地址</el-button>
              </el-col>
              <el-col :span="18">
                <el-form-item prop="goods_gallery">
                  <el-table
                    :data="addForm.goods_gallery"
                  >
                    <el-table-column
                      prop="addr"
                      label="地址"
                      width="180">
                    </el-table-column>
                    <el-table-column label="操作" class="btns">
                      <template slot-scope="scope">
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                   @click="removeGoodsGallery(scope.$index)">删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="详情图" name="3">
            <el-row>
              <el-col :span="6" style="margin-top: 25px;">
                <el-form-item label="地址" prop="image_url" label-width="70px" label-position="top">
                  <el-input v-model="add_image.addr"></el-input>
                </el-form-item>
                <el-button type="primary" @click="addGoodsImage">添加地址</el-button>
                <!--<el-upload
                  :action="uploadUrl"
                  :on-preview="handleImgPreview"
                  :on-remove="handleImgRemove"
                  list-type="picture"
                  :headers="imgUploadHeaders"
                  :on-success="handleImgUploadSuccess">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>-->
              </el-col>
              <el-col :span="18">
                <el-form-item prop="goods_image">
                  <el-table
                    :data="addForm.goods_image"
                  >
                    <el-table-column
                      prop="addr"
                      label="地址"
                      width="180">
                    </el-table-column>
                    <el-table-column label="操作" class="btns">
                      <template slot-scope="scope">
                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                   @click="removeGoodsImage(scope.$index)">删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览弹窗 -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDialogVisible"
      width="50%">
      <img :src="previewImgUrl" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import BreadcrumbNav from '../../common/BreadcrumbNav'
// import GoodsBasePane from './GoodsBasePane'
import { getCategoriesListRequest, addGoodsRequest, getGoodsDetail, updateGoodsRequest } from '../../../network/goods'
import { getShopList } from '../../../network/shop'

export default {
  name: 'GoodsAddB',
  components: {
    BreadcrumbNav
    // GoodsBasePane
  },
  data () {
    return {
      menuTitle: '添加商品',
      activeIndex: '0',
      addForm: {
        category_id: '',
        goods_brief: '',
        goods_desc: '',
        goods_sn: '',
        goods_type: '',
        is_on_sale: 1,
        list_pic_url: '',
        name: '',
        primary_pic_url: '',
        retail_price: '',
        sort_order: 1,
        goods_attrs: [],
        goods_gallery: [],
        goods_image: [],
        shop_code: ''
      },
      add_gallery: { addr: '' },
      add_image: { addr: '' },
      add_attrs: {
        name: '',
        value: ''
      },
      addFormRules: {
        name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        retail_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        category_id: [
          {
            required: true,
            message: '请选择商品分类',
            trigger: 'blur'
          }
        ],
        shop_code: [
          {
            required: true,
            message: '请选择店铺',
            trigger: 'blur'
          }
        ],
        goods_type: [
          {
            required: true,
            message: '请选择商品类型',
            trigger: 'blur'
          }
        ],
        goods_brief: [
          {
            required: true,
            message: '请输入商品简介',
            trigger: 'blur'
          }
        ],
        list_pic_url: [
          {
            required: true,
            message: '请输入缩略图地址',
            trigger: 'blur'
          }
        ],
        primary_pic_url: [
          {
            required: true,
            message: '请输入主图地址',
            trigger: 'blur'
          }
        ],
        goods_sn: [
          {
            required: true,
            message: '请输入商品编码',
            trigger: 'blur'
          }
        ],
        sort_order: [
          {
            required: true,
            message: '请输入排序序号',
            trigger: 'blur'
          }
        ]
      },
      // 分类列表
      categoryList: [],
      // 店铺列表
      shopList: [],
      // 商品类型
      goodsTypes: [{
        label: '普通',
        value: 0
      }, {
        label: '新品',
        value: 1
      }, {
        label: '热门',
        value: 2
      }, {
        label: '轮播',
        value: 3
      }],
      uploadUrl: 'https://www.liulongbin.top:8888/api/private/v1',
      imgUploadHeaders: { // 上传图片控件的header
        Authorization: sessionStorage.getItem('token')
      },
      previewImgUrl: '',
      previewDialogVisible: false,
      fileList: []
    }
  },
  computed: {},
  created () {
    console.log('this.$route.query.id', this.$route.query.id)
    if (this.$route.query.id !== undefined) {
      this.menuTitle = '更新商品'
    }
    this.getCategoriesList(this.$route.query.id)
  },
  methods: {
    addGoodsAttr () {
      console.log('this.add_form.add_attr:', this.add_attrs)
      this.addForm.goods_attrs.push(this.add_attrs)
      this.add_attrs = {
        name: '',
        value: '',
        id: 0
      }
    },
    removeGoodsAttr (index) {
      console.log('goods index:', index)
      this.addForm.goods_attrs.splice(index, 1)
    },
    addGoodsGallery () {
      this.addForm.goods_gallery.push(this.add_gallery)
      this.add_gallery = {
        addr: '',
        id: 0
      }
    },
    removeGoodsGallery (index) {
      this.addForm.goods_gallery.splice(index, 1)
    },
    addGoodsImage () {
      this.addForm.goods_image.push(this.add_image)
      this.add_image = {
        addr: '',
        id: 0
      }
    },
    removeGoodsImage (index) {
      this.addForm.goods_image.splice(index, 1)
    },
    getCategoriesList (id) {
      getCategoriesListRequest({ page: 1, size: 100 }).then(res => {
        if (res.status !== 200) {
          return this.alertMessage('获取分类列表失败', 'error')
        }
        this.categoryList = res.data.data.data
        console.log('category is:', this.categoryList)
        getShopList({}).then(shopRes => {
          if (shopRes.status !== 200) {
            return this.alertMessage('获取分类列表失败', 'error')
          }
          this.shopList = shopRes.data.data.data
          if (id !== undefined) {
            this.loadGoodsDetail(id)
          } else {
            if (this.categoryList.length > 0) {
              this.addForm.category_id = this.categoryList[0].category_id
            }
            if (this.shopList.length > 0) {
              this.addForm.shop_code = this.shopList[0].code
            }
          }
        })
      })
    },
    loadGoodsDetail (id) {
      getGoodsDetail(id).then(res => {
        // 更新失败
        if (res.status !== 200) {
          this.isLoading = false
          return this.alertMessage('获取商品信息失败', 'error')
        }
        console.log('update goods detail:', res.data.data)
        this.initGoodsParam(res.data.data)
      })
    },
    initGoodsParam (data) {
      for (let i = 0; i < data.gallery.length; i++) {
        this.addForm.goods_gallery.push({
          addr: data.gallery[i].img_url,
          id: data.gallery[i].id
        })
      }
      for (let i = 0; i < data.imageText.length; i++) {
        this.addForm.goods_image.push({
          addr: data.imageText[i].img_url,
          id: data.imageText[i].id
        })
      }
      this.addForm.goods_desc = data.info.goods_desc
      this.addForm.category_id = data.info.category_id
      this.addForm.goods_attrs = data.attribute
      this.addForm.goods_brief = data.info.goods_brief
      this.addForm.goods_sn = data.info.goods_sn
      this.addForm.goods_type = data.info.goods_type
      this.addForm.is_on_sale = data.info.is_on_sale
      this.addForm.list_pic_url = data.info.list_pic_url
      this.addForm.name = data.info.name
      this.addForm.primary_pic_url = data.info.primary_pic_url
      this.addForm.retail_price = Math.round(data.info.retail_price * 100) / 100
      this.addForm.sort_order = data.info.sort_order
      this.addForm.shop_code = data.info.shop_code
      console.log('---edit init form:', this.addForm)
    },
    // tab标签页发生切换
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0') {
        // this.alertMessage('请先选择商品分类', 'error')
        // return false
      }
    },
    // 点击切换左侧标签页
    tabClicked () {
      // 访问的是商品参数面板
    },
    // 点击按钮添加商品
    submitGoods () {
      this.$confirm('是否要提交该商品', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.finishCommit()
      }).catch(() => {
        this.alertMessage('已取消提交', 'info')
      })
    },
    finishCommit () {
      this.activeIndex = '4'
      console.log('goods add detail:', this.addForm)
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return this.alertMessage('请填写必要的表单项', 'error')
        }
        const params = this.createGoodsParam()
        console.log('----create param is:', params)
        if (this.$route.query.id === undefined) {
          this.addGoods(params)
        } else {
          this.updateGoods(params)
        }
      })
    },
    addGoods (params) {
      console.log('add goods params:', params)
      addGoodsRequest(params).then(res => {
        const result = res.data
        console.log('添加商品', result)
        if (res.status !== 200) {
          return this.alertMessage('添加失败', 'error')
        }
        this.alertMessage('添加成功', 'success')
        this.activeIndex = '5'
        this.$refs.addFormRef.resetFields()
        // this.$router.push('/goods')
      })
    },
    updateGoods (params) {
      console.log('add goods params:', params)
      updateGoodsRequest(this.$route.query.id, params).then(res => {
        const result = res.data
        console.log('修改商品', result)
        if (res.status !== 200) {
          return this.alertMessage('修改失败', 'error')
        }
        this.alertMessage('修改成功', 'success')
        this.activeIndex = '5'
        this.$refs.addFormRef.resetFields()
        // this.$router.push('/goods')
      })
    },
    createGoodsParam () {
      const gallery = []
      const imageText = []
      for (let i = 0; i < this.addForm.goods_gallery.length; i++) {
        gallery.push({
          img_url: this.addForm.goods_gallery[i].addr,
          img_type: 1,
          sort_order: i + 1,
          id: this.addForm.goods_gallery[i].id
        })
      }
      for (let i = 0; i < this.addForm.goods_image.length; i++) {
        imageText.push({
          img_url: this.addForm.goods_image[i].addr,
          img_type: 2,
          sort_order: i + 1,
          id: this.addForm.goods_image[i].id
        })
      }
      return {
        info: {
          category_id: this.addForm.category_id,
          goods_brief: this.addForm.goods_brief,
          goods_desc: this.addForm.goods_desc,
          goods_sn: this.addForm.goods_sn,
          goods_type: this.addForm.goods_type,
          is_on_sale: this.addForm.is_on_sale,
          list_pic_url: this.addForm.list_pic_url,
          name: this.addForm.name,
          primary_pic_url: this.addForm.primary_pic_url,
          retail_price: Math.round(this.addForm.retail_price * 100) / 100,
          sort_order: this.addForm.sort_order,
          shop_code: this.addForm.shop_code
        },
        gallery: gallery,
        attribute: this.addForm.goods_attrs,
        imageText: imageText
      }
    },
    // 处理图片预览效果
    handleImgPreview (file) {
      console.log('预览', file)
      // this.previewImgUrl = file.response.data.url
      this.previewDialogVisible = true
    },

    // 处理移除图片的操作
    handleImgRemove (file) {
      // file表示将要被移除的文件
      /* console.log('将要被移除的文件:', file)
      const removeUrl = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(item => {
        return item.tmp_path === removeUrl
      })
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm) */
      this.fileList = this.fileList.filter(x => x.uid !== file.uid)
      this.addForm.pics = this.addForm.pics.filter(x => x.pic !== file.response.data.tmp_path)
    },

    // 监听图片上传成功
    handleImgUploadSuccess (response, file, fileList) {
      this.fileList = fileList
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addForm.pics.push(picInfo)
    },
    // 点击预览图片按钮时的回调函数
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.previewDialogVisible = true
    },
    // 点击了移除按钮时的回调函数
    handleRemove (file) {
      this.fileList = this.fileList.filter(x => x.uid !== file.uid)
      this.addForm.pics = this.addForm.pics.filter(x => x.pic !== file.response.data.tmp_path)
    },
    // 上传成功的回调函数
    onUploadSuccess (response, file, fileList) {
      if (response.meta.status !== 200) return this.$message.error('上传图片失败！')

      this.fileList = fileList
      this.addForm.pics.push({ pic: response.data.tmp_path })
      console.log(this.addForm.pics)
    }
  }
}
</script>

<style>
.el-input-number.is-without-controls .el-input__inner {
  width: 100%;
  line-height: 30px;
  height: 28px;
}
</style>
